package com.knowswift.security.handler.fail;

import com.knowswift.common.common.BaseResponse;
import com.knowswift.security.exception.AuthException;
import com.knowswift.security.handler.JsonResponseHandler;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @company https://www.knowswift.com
 */
@Component
public class LoginFailureHandler extends JsonResponseHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        BaseResponse<?> result = BaseResponse.base(BaseResponse.LOGIN_FAIL_CODE, e.getMessage(), null);
        if (e instanceof AuthException) {
            AuthException authException = (AuthException) e;
            BaseResponse<?> result1 = authException.getBaseResponse();
            result = result1 == null ? result : result1;
        } else if (e.getCause() instanceof AuthException) {
            AuthException authException = (AuthException) e.getCause();
            BaseResponse<?> result1 = authException.getBaseResponse();
            result = result1 == null ? result : result1;
        }
        sendResponse(httpServletResponse, result);
    }
}
